import { thin } from "../thin3.mjs";
import { clearafterqueue } from "./delay_render.mjs";
export default function ({
  url,
  data,
  dataType = "json",
  type = "POST",
  contentType = "application/JSON",
  success,
  error,
}) {
  let xhr = new XMLHttpRequest();
  let done, fail, always;
  function ajax() {
    xhr.onreadystatechange = function () {
      if (xhr.readyState !== 4) {
      } else if (xhr.status === 200) {
        let d = xhr.responseText;
        // console.log({ xhr });
        switch (dataType) {
          case "json":
            if (success) success(JSON.parse(d), xhr.statusText, xhr);
            if (done) done(JSON.parse(d), xhr.statusText, xhr);
            break;
          default:
            if (success) success(d, xhr.statusText, xhr);
            if (done) done(d, xhr.statusText, xhr);
            break;
        }
      } else {
        try {
          xhr.responseJSON = JSON.parse(xhr.responseText);
        } catch {}
        if (fail) fail(xhr, xhr.statusText);
        if (error) error(xhr, xhr.statusText);
      }
      clearafterqueue();
    };

    switch (type.toUpperCase()) {
      case "POST":
        //console.log(options);
        xhr.open(type, url, true);
        xhr.setRequestHeader("Content-Type", contentType);
        switch (contentType) {
          case "application/x-www-form-urlencoded":
            xhr.send(thin.serialize(data));
            break;
          default:
            //console.log(options.contentType);
            xhr.send(JSON.stringify(data));
            break;
        }
        break;
      case "GET":
        xhr.open(type, `${url}?${thin.serialize(data)}`);
        xhr.send();
        break;
      default:
        xhr.open(type, url, true);
        xhr.send();
        break;
    }
    return this;
  }

  return ajax.call({
    done: function (fn) {
      done = fn;
      return this;
    },
    fail: function (fn) {
      fail = fn;
      return this;
    },
    abort: function () {
      xhr.abort();
      return this;
    },
  });
}
